package com.bestom.producetest.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bestom.producetest.R;
import com.bestom.producetest.utils.AppUtil;
import com.bestom.producetest.utils.ProperTiesUtils;
import com.bestom.producetest.view.CameraView;

import java.io.IOException;

import static com.bestom.producetest.base.App.configfilename;

/**
 * Test camera
 */
public class CameraActivity extends AppCompatActivity {
    private static final String TAG = "CameraActivity";
    private Activity mActivity;
    Intent mIntent;
    TextView camView;
    TextView errHint;
    Button swBtn, sw2Button;
    Button closeBtn;
    CameraView cameraView;
    int cameraCount = 0;
    private Camera camera;
    /**
     * Front Camera Tag
     */
    private static final int FRONT = 0;
    /**
     * back Camera Tag
     */
    private static final int BACK = 1;
    /**
     * The currently open camera flag
     */
    private int currentCameraType = -1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // Hide the bottom navigation bar
        if (AppUtil.hasNavBar(this)) {
            AppUtil.hideBottomUIMenu(this);
        }
        setContentView(R.layout.activity_camera);

        mActivity = this;
        mIntent = new Intent();
        initView();
        initCamera();
    }

    private void initView() {
        camView = findViewById(R.id.cam_view);
        errHint = findViewById(R.id.err_hint);
        swBtn = findViewById(R.id.switch_btn);
        swBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeCamera();
            }
        });
        sw2Button = findViewById(R.id.switch2cameras_btn);
        sw2Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                open2cameras();
            }
        });
        closeBtn = findViewById(R.id.close_btn);
        findViewById(R.id.default_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCan) {
                    new AlertDialog.Builder(CameraActivity.this)
                            .setTitle(R.string.camera_management)
                            .setMessage(R.string.ban_cameras)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // Disable the camera
                                    ProperTiesUtils.setProp("persist.sys.disablecamera", "true");
                                    // After setting system properties, you must restart the current page
                                    reStartActivity();
                                }
                            })
                            .setNegativeButton(R.string.no, null)
                            .show();
                } else {
                    Toast.makeText(getApplicationContext(), R.string.disenable, Toast.LENGTH_SHORT).show();
                }
            }
        });
        findViewById(R.id.default_open).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (isCan) {
                    Toast.makeText(getApplicationContext(), R.string.enable, Toast.LENGTH_SHORT).show();
                } else {
                    new AlertDialog.Builder(CameraActivity.this)
                            .setTitle(R.string.camera_management)
                            .setMessage(R.string.enable_cameras)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // Make the camera available
                                    ProperTiesUtils.setProp("persist.sys.disablecamera", "false");
                                    // After setting system properties, you must restart the current page
                                    reStartActivity();
                                }
                            })
                            .setNegativeButton(R.string.no, null)
                            .show();
                }
            }
        });
        cameraView = findViewById(R.id.camera_view);
        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("request", "camera");
                setResult(001, intent);
                finish();
            }
        });
    }

    private boolean isCan;

    private void initCamera() {

        cameraCount = Camera.getNumberOfCameras();
        if (cameraCount >= 2) {
            swBtn.setVisibility(View.VISIBLE);
            if (Integer.valueOf(ProperTiesUtils.getProperties(mActivity, configfilename, "RK3399server_2camera")) == 1) {
                sw2Button.setVisibility(View.VISIBLE);
            }
        }
        try {
            camera = openCamera(FRONT);
            Camera.Parameters parameters = camera.getParameters();
            parameters.setPreviewSize(1920, 1080);
            camera.setParameters(parameters);
            camView.setText(R.string.front_camera);
            mIntent.putExtra("camera", "frontcamera");
            isCan = true;
        } catch (Exception e) {
            e.printStackTrace();
            errHint.setVisibility(View.VISIBLE);
        }

        cameraView.init(camera);
    }

    /**
     * Check if the device has a camera
     */
    private boolean checkCamera() {
        return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
    }

    /**
     * open camera
     */
    private Camera openCamera(int type) {

        currentCameraType = type;
        if (type == FRONT) {
            return Camera.open(currentCameraType);
        } else if (type == BACK) {
            return Camera.open(currentCameraType);
        }
        return null;
    }

    /**
     * Turn on both cameras
     */
    private void open2cameras() {
        Intent intent = new Intent();
        intent.putExtra("request", "2camera");

        setResult(001, intent);
        finish();
    }

    /**
     * Switch Camera
     */
    private void changeCamera() {
        try {
            camera.stopPreview();
            camera.release();
            if (currentCameraType == FRONT) {
                camera = openCamera(BACK);
                camView.setText(R.string.back_camera);
                mIntent.putExtra("request", "frontcamera");
                errHint.setVisibility(View.GONE);
            } else if (currentCameraType == BACK) {
                camera = openCamera(FRONT);
                camView.setText(R.string.front_camera);
                mIntent.putExtra("request", "backcamera");
                errHint.setVisibility(View.GONE);
            }
            camera.setPreviewTexture(cameraView.getSurfaceTexture());
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
            errHint.setVisibility(View.VISIBLE);
        }
    }

    private void reStartActivity() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
}
